package org.dromara.system.controller;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import cn.dev33.satoken.annotation.SaIgnore;
import lombok.RequiredArgsConstructor;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.validation.constraints.*;
import cn.dev33.satoken.annotation.SaCheckPermission;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.dromara.system.domain.DeviceDetail;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.validation.annotation.Validated;
import org.dromara.common.idempotent.annotation.RepeatSubmit;
import org.dromara.common.log.annotation.Log;
import org.dromara.common.web.core.BaseController;
import org.dromara.common.mybatis.core.page.PageQuery;
import org.dromara.common.core.domain.R;
import org.dromara.common.core.validate.AddGroup;
import org.dromara.common.core.validate.EditGroup;
import org.dromara.common.log.enums.BusinessType;
import org.dromara.common.excel.utils.ExcelUtil;
import org.dromara.system.domain.vo.DeviceDetailVo;
import org.dromara.system.domain.bo.DeviceDetailBo;
import org.dromara.system.service.IDeviceDetailService;
import org.dromara.common.mybatis.core.page.TableDataInfo;
import org.springframework.web.multipart.MultipartFile;

/**
 * 设备详细信息
 *
 * @author Lion Li
 * @date 2024-12-23
 */
@Validated
@RequiredArgsConstructor
@RestController
@RequestMapping("/system/deviceDetail")
public class DeviceDetailController extends BaseController {

    private final IDeviceDetailService deviceDetailService;


    @SaIgnore
    @PostMapping("/uploadExcel")
    @Transactional(rollbackFor = Exception.class)
    public R<String> upload(@RequestParam("file") MultipartFile file) throws Exception {
        // 判断文件类型
        if (!file.getOriginalFilename().endsWith(".xlsx") && !file.getOriginalFilename().endsWith(".xls")) {
            return R.fail("请上传 .xlsx 或 .xls 文件");
        }

        // Step 1: Parse Excel file
        InputStream inputStream = file.getInputStream();
        Workbook workbook;
        if (file.getOriginalFilename().endsWith(".xlsx")) {
            workbook = new XSSFWorkbook(inputStream); // For .xlsx files
        } else {
            workbook = new HSSFWorkbook(inputStream); // For .xls files
        }

        Sheet sheet = workbook.getSheetAt(0); // Read the first sheet
        List<DeviceDetail> entityList = new ArrayList<>();

        int rowCount = sheet.getPhysicalNumberOfRows();
        if (rowCount <= 1) {
            return R.fail("Excel 数据为空或格式不正确");
        }

        // Step 2: Read header row and map column names to fields
        Row headerRow = sheet.getRow(0);
        int columnCount = headerRow.getPhysicalNumberOfCells();

        // Map: Column name -> Column index
        Map<String, Integer> columnMapping = new HashMap<>();
        for (int i = 0; i < columnCount; i++) {
            Cell cell = headerRow.getCell(i);
            if (cell != null) {
                columnMapping.put(cell.getStringCellValue().trim(), i);
            }
        }

//        // Ensure required columns are present
//        if (!columnMapping.containsKey("Field1") || !columnMapping.containsKey("Field2")) {
//            return R.fail("Excel 缺少必要的列：Field1 或 Field2");
//        }

        // Step 3: Read data rows
        for (int i = 1; i < rowCount; i++) {
            Row row = sheet.getRow(i);
            if (row == null) {
                continue; // Skip empty rows
            }

            DeviceDetail entity = new DeviceDetail();

            // Dynamically set fields based on column names
            if (columnMapping.containsKey("充气介质")) {
                Cell cell = row.getCell(columnMapping.get("充气介质"));
                entity.setChargingMedium(cell != null ? cell.toString() : null);
            }
            if (columnMapping.containsKey("制造单位")) {
                Cell cell = row.getCell(columnMapping.get("制造单位"));
                entity.setManufacturer(cell != null ? cell.toString() : null);
            }
            if (columnMapping.containsKey("下次检验日期")) {
                Cell cell = row.getCell(columnMapping.get("下次检验日期"));
                entity.setNextInspectionDate(cell != null ? cell.toString() : null);
            }

            if (columnMapping.containsKey("充装单位")) {
                Cell cell = row.getCell(columnMapping.get("充装单位"));
                entity.setChargingUnit(cell != null ? cell.toString() : null);
            }
            if (columnMapping.containsKey("状态")) {
                Cell cell = row.getCell(columnMapping.get("状态"));
                entity.setStatus(cell != null ? cell.toString() : null);
            }
            if (columnMapping.containsKey("检验日期")) {
                Cell cell = row.getCell(columnMapping.get("检验日期"));
                entity.setInspectionDate(cell != null ? cell.toString() : null);
            }
            if (columnMapping.containsKey("设备品种")) {
                Cell cell = row.getCell(columnMapping.get("设备品种"));
                entity.setDeviceType(cell != null ? cell.toString() : null);
            }
            if (columnMapping.containsKey("制造日期")) {
                Cell cell = row.getCell(columnMapping.get("制造日期"));
                entity.setManufactureDate(cell != null ? cell.toString() : null);
            }
            if (columnMapping.containsKey("单位内编号")) {
                Cell cell = row.getCell(columnMapping.get("单位内编号"));
                entity.setUnitNumber(cell != null ? cell.toString() : null);
            }
            if (columnMapping.containsKey("产品编号")) {
                Cell cell = row.getCell(columnMapping.get("产品编号"));
                entity.setProductNumber(cell != null ? cell.toString() : null);
            }
            if (columnMapping.containsKey("标签号")) {
                Cell cell = row.getCell(columnMapping.get("标签号"));
                entity.setLabelNumber(cell != null ? cell.toString() : null);
            }
            if (columnMapping.containsKey("公称工作压力(MPa)")) {
                Cell cell = row.getCell(columnMapping.get("公称工作压力(MPa)"));
                entity.setNominalPower(cell != null ? cell.toString() : null);
            }
            if (columnMapping.containsKey("容积")) {
                Cell cell = row.getCell(columnMapping.get("容积"));
                entity.setWarrantyPeriod(cell != null ? cell.toString() : null);
            }

            if (columnMapping.containsKey("登记证编号")) {
                Cell cell = row.getCell(columnMapping.get("登记证编号"));
                entity.setRegistrationNumber(cell != null ? cell.toString() : null);
            }
            if (columnMapping.containsKey("二维码号")) {
                Cell cell = row.getCell(columnMapping.get("二维码号"));
                entity.setQrCodeNumber(cell != null ? cell.toString() : null);
            }

            entityList.add(entity);
        }

        workbook.close();

        // Step 4: Insert data into database
        if (!entityList.isEmpty()) {
            deviceDetailService.saveBatch(entityList);
        } else {
            return R.fail("Excel 文件内容为空或无法解析");
        }

        return R.ok("文件上传并成功导入数据库");
    }


    /**
     * 查询设备详细信息列表
     */
    @SaCheckPermission("system:DeviceDetail:list")
    @GetMapping("/list")
    public TableDataInfo<DeviceDetailVo> list(DeviceDetailBo bo, PageQuery pageQuery) {
        return deviceDetailService.queryPageList(bo, pageQuery);
    }

    /**
     * 导出设备详细信息列表
     */
    @SaCheckPermission("system:DeviceDetail:export")
    @Log(title = "设备详细信息", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(DeviceDetailBo bo, HttpServletResponse response) {
        List<DeviceDetailVo> list = deviceDetailService.queryList(bo);
        ExcelUtil.exportExcel(list, "设备详细信息", DeviceDetailVo.class, response);
    }

    /**
     * 获取设备详细信息详细信息
     *
     * @param productNumber 主键
     */
    @SaCheckPermission("system:DeviceDetail:query")
    @GetMapping("/{productNumber}")
    public R<DeviceDetailVo> getInfo(@NotNull(message = "主键不能为空")
                                     @PathVariable String productNumber) {
        return R.ok(deviceDetailService.queryById(productNumber));
    }

    /**
     * 新增设备详细信息
     */
    @SaCheckPermission("system:DeviceDetail:add")
    @Log(title = "设备详细信息", businessType = BusinessType.INSERT)
    @RepeatSubmit()
    @PostMapping()
    public R<Void> add(@Validated(AddGroup.class) @RequestBody DeviceDetailBo bo) {
        return toAjax(deviceDetailService.insertByBo(bo));
    }

    /**
     * 修改设备详细信息
     */
    @SaCheckPermission("system:DeviceDetail:edit")
    @Log(title = "设备详细信息", businessType = BusinessType.UPDATE)
    @RepeatSubmit()
    @PutMapping()
    public R<Void> edit(@Validated(EditGroup.class) @RequestBody DeviceDetailBo bo) {
        return toAjax(deviceDetailService.updateByBo(bo));
    }

    /**
     * 删除设备详细信息
     *
     * @param productNumbers 主键串
     */
    @SaCheckPermission("system:DeviceDetail:remove")
    @Log(title = "设备详细信息", businessType = BusinessType.DELETE)
    @DeleteMapping("/{productNumbers}")
    public R<Void> remove(@NotEmpty(message = "主键不能为空")
                          @PathVariable String[] productNumbers) {
        return toAjax(deviceDetailService.deleteWithValidByIds(List.of(productNumbers), true));
    }
}
